import { nanoid } from 'nanoid'
import type { FileMenu } from '@/views/floderMenu/types'

/**
 *  句柄处理函数
 * @param handle 单个句柄
 * @returns
 */
async function processHandle(handle: any) {
  handle.id = nanoid()
  handle.visible = true
  if (handle.kind === 'file') {
    return handle
  }
  handle.children = []
  for await (const item of handle.entries()) {
    // console.log(item)
    // 0：文件名1：下一个句柄
    handle.children.push(await processHandle(item[1]))
  }
  return handle
}
/**
 * 递归map数据
 * @param data 原始数据
 * @returns
 */
function recursiveMap(data: FileMenu) {
  return data.map((item) => {
    const newItem: any = {
      id: item.id,
      name: item.name,
      kind: item.kind,
      visible: item.visible
    }
    if (item.children) {
      newItem.children = recursiveMap(item.children)
    }
    return newItem
  })
}
/**
 * 处理里隐藏菜单
 * @param keyWord 搜索关键字
 * @param data 待搜索数据源
 * @param attribute 关键字所属属性
 */
function filterTreeData(
  keyWord: string,
  data: FileMenu,
  attribute: string = 'name'
) {
  const openMenu: Array<string> = []
  const Traverse = (
    keyWord: string,
    data: FileMenu,
    attribute: string = 'name'
  ) => {
    data.forEach((item) => {
      if (item.children && item.children.length > 0) {
        Traverse(keyWord, item.children as FileMenu)
        item.visible = item.children.some((item: any) => item.visible)
        if (item.visible) openMenu.push(item.id)
      } else {
        item.visible = keyWord
          ? (item[attribute] as string)
              .toLowerCase()
              .includes(keyWord.toLowerCase())
          : true
      }
    })
  }
  Traverse(keyWord, data, attribute)
  return openMenu
}
/**
 *
 * @param id 要查找数据对应的id
 * @param list 要查询的树形结构数组
 * @returns 返回该数据或null
 */
function findItemById(id: string, list: FileMenu) {
  for (const node of list) {
    if (node.id === id) {
      return node
    }
    if (node.children) {
      const foundNode: any = findItemById(id, node.children as FileMenu)
      if (foundNode) {
        return foundNode
      }
    }
  }
  return null
}

export { processHandle, recursiveMap, findItemById, filterTreeData }
